package com.apes.framework.plugin.soe.metadata;

import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.Name;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 功能：凭证类型
 *
 * @author xul
 * @create 2018-09-21 14:05
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = BusinessField.CONST_TABLE_NAME)
public class BusinessField extends Model {
    public static final String CONST_TABLE_NAME = "soe_business_field";

    @Id
    @Column(name = "id", length = 64)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "模型字段对照表")
    @Comment("通用名")
    private String id;

    @Name
    @Column(name = "description", nullable = false, length = 120)
    @Comment("描述")
    private String description;

    @Comment("业务模型")
    @ManyToOne(fetch = FetchType.LAZY)

    @JoinColumn(name = "business_type", referencedColumnName = "id", nullable = false)
    private BusinessType businessType;

    @OneToMany(mappedBy = "businessField", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<BusinessFieldItem> businessFieldItemList =  new ArrayList<>();

    public List<BusinessFieldItem> getBusinessFieldItemList() {
        if(businessFieldItemList == null) businessFieldItemList = new ArrayList<>();
        for (BusinessFieldItem businessFieldItem : businessFieldItemList) {
            businessFieldItem.setBusinessField(this);
        }
        return businessFieldItemList;
    }

    public String businessTypeCode(String businessTypeId) {
        BusinessFieldItem businessFieldItem = getBusinessFieldItemList().stream()
                .filter((bfi -> bfi.getBusinessType().getId().equals(businessTypeId))).findFirst().orElse(null);
        if (businessFieldItem != null) return businessFieldItem.getCode();
        return id;
    }
}
